/**
 * 
 */
package com.bieber.smartpost.invoke;

import com.bieber.smartpost.httpcore.Request;
import com.bieber.smartpost.httpcore.Response;
import com.bieber.smartpost.model.RequestEntity;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author bieber
 *HTTP请求的单元
 */
public class HttpProxy {

    /**
     *执行前端的请求
     * @param entity
     * @param cookies
     * @return
     * @throws IOException
     */
    public static Response doRequest(RequestEntity entity,String cookies) throws Exception {
        Request request = new Request(entity.getUrl(),entity.getParametersType());
        if(cookies.length()>0){
            request.setHeader("Cookie",cookies);
        }
        if(entity.getHeader()!=null){
            for(Map<String,String> header:entity.getHeader()){
                for(Map.Entry<String,String> entry : header.entrySet()){
                    request.setHeader(entry.getKey(),entry.getValue());
                }
            }
        }
        if("GET".equalsIgnoreCase(entity.getType())){
          return doGet(request,entity);
        }else{
          return doPost(request,entity);
        }
    }


    private static Response doPost(Request request,RequestEntity entity) throws Exception {
        if("form".equalsIgnoreCase(entity.getParametersType())){
            if(entity.getParams()!=null){
                return request.post(convertParams(entity.getParams()));
            }else{
                return  request.post(new HashMap<String, String>());
            }
        }else{
            if(entity.getParams()==null){
                return request.post();
            }
            return request.post(entity.getParams().toString());
        }
    }

    private static Map<String,String> convertParams(Object requestParam){
        if(String.class.isAssignableFrom(requestParam.getClass())){
            return new HashMap<String,String>();
        }
        List<Map<String,String>> params = (List<Map<String, String>>) requestParam;
        Map<String,String> paramMap = new HashMap<String, String>();
        for(Map<String,String> param:params){
            for(Map.Entry<String,String> entry:param.entrySet()){
                paramMap.put(entry.getKey(),entry.getValue());
            }
        }
        return paramMap;
    }

    private static  Response doGet(Request request,RequestEntity entity) throws Exception {
        if("raw".equalsIgnoreCase(entity.getParametersType())){
            return request.get(entity.getParams().toString());
        }else{
            if(entity.getParams()!=null){
                return request.get(convertParams(entity.getParams()));
            }else{
                return  request.get(new HashMap<String, String>());
            }
        }
    }
}
